package conexaobd;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class ConectaBD {
    public static Connection conn;
    private static PreparedStatement pst;
    private static ResultSet rs;

    public static void abreConexao(){
        try{
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(
                  "jdbc:mysql://localhost/libertaslibrary?user=libraryadmin&password=libertas123");
                  // "jdbc:mysql://localhost/libertaslibrary?user=root&password=1234");
            System.out.println("Conexão realizada com sucesso!");
        } catch(Exception e){
            System.out.println("Erro: " + e.getMessage());
        }
    }
   
    public static void executaSQL(String sql){
        try{
          
            pst = conn.prepareStatement(sql);
            pst.executeUpdate();
        }catch (Exception erro){
            System.out.println("Erro: " + erro.getMessage());
        }
    }
    
    public static ResultSet executaConsulta(String sql){
        try{
            pst = conn.prepareStatement(sql);
            rs = pst.executeQuery();
            return rs;
            
        }catch(Exception erro){
            System.out.println("Erro: " + erro.getMessage());
            return null;
        }
    }
    
    public static PreparedStatement prepare(String sql){
        try{
            return conn.prepareStatement(sql);
        }catch(Exception erro){
            System.out.println("Erro: " + erro.getMessage());
            return null;
        }
    }
    public static void fechaConexao(){
        try {
            if(rs!=null)
                rs.close();
            if(pst!=null)
                pst.close();
            
            if(conn!=null)
                conn.close();
        } catch (Exception erro) {
            System.out.println("Erro " + erro.getMessage());
        } 
    }
}